<template>
  <div ref="wordCloud" style="width:100%;height:350px;"/>
</template>

<script>
import echarts from 'echarts'
import resize from '@/utils/resize'
import { setWatermark } from '@/utils'
import 'echarts-wordcloud/dist/echarts-wordcloud'
import 'echarts-wordcloud/dist/echarts-wordcloud.min'

export default {
  mixins: [resize],
  props: {
    chartData: {
      type: Array,
      default: () => {}
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null,
      data: []
    }
  },
  watch: {
    chartData(val) {
      this.data = []
      this.data = val

      if (this.chart) {
        this.setOptions()
      } else {
        this.initChart()
      }
    }
  },
  mounted() {
    this.data = this.chartData
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    setOptions() {
      this.chart.setOption({
        backgroundColor: {
          image: setWatermark(),
          repeat: 'repeat'
        },
        title: {
          text: this.title,
          x: 'center'
        },
        tooltip: {
          show: true
        },
        toolbox: {
          right: 15,
          feature: {
            saveAsImage: {
              backgroundColor: '#FFF'
            },
            dataView: {
              show: true
            }
          }
        },
        series: [{
          name: this.title,
          type: 'wordCloud',
          gridSize: 6,
          shape: 'diamond',
          sizeRange: [12, 50],
          textStyle: {
            normal: {
              color: function() {
                return 'rgb(' + [
                  Math.round(Math.random() * 160),
                  Math.round(Math.random() * 160),
                  Math.round(Math.random() * 160)
                ].join(',') + ')'
              }
            },
            emphasis: {
              shadowBlur: 10,
              shadowColor: '#333'
            }
          },
          data: this.data
        }]
      })
    },
    initChart() {
      this.chart = echarts.init(this.$refs.wordCloud)
      setTimeout(() => {
        this.setOptions()
      }, 300)
    }
  }
}
</script>
